package com.nicolasprof.profgallery.layers {
	import com.mosesSupposes.bitmap.InteractivePNG;
	import com.nicolasprof.profgallery.Engine;
	import com.nicolasprof.profgallery.layers.LayerLoader;

	import flash.display.Bitmap;
	import flash.display.LoaderInfo;
	import flash.events.Event;
	import flash.net.URLRequest;

	/**
	 * @author Nicolas Prof
	 */
	public class LayerManager extends Object {

		private var _engine : Engine;

		
		public function LayerManager($parent : Engine) {
			var config : XML = Engine.CONFIG_XML;
			_engine = $parent;
			
			addLayer(config.body.@background, 0);
			addLayer(config.body.@foreground, _engine.numChildren);
		}	
		private function addLayer($url : String, $index : int) : void {
			if($url == "") return;
			
			var loader : LayerLoader = new LayerLoader();
			loader.layer = $index;
			var request : URLRequest = new URLRequest($url);
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onComplete);
			loader.load(request);
		}		
		/**
		 * Events
		 */
		private function onComplete(e : Event) : void {
			var ldr : LoaderInfo = e.currentTarget as LoaderInfo;
			ldr.removeEventListener(Event.COMPLETE, onComplete);
			
			var index : int = LayerLoader(ldr.loader).layer;
			
			switch(Object(ldr.content).constructor){
				case Bitmap : 
					var holder : InteractivePNG = new InteractivePNG();
					holder.addChild(ldr.content);
					_engine.addChildAt(holder, index);
					break;
				default :
					_engine.addChildAt(ldr.content, index);
					break;
			}
			
		}
	}
}
